package pl.edu.agh.neuraleconomy.core.experiment.statistics;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import pl.edu.agh.neuraleconomy.common.utils.FileUtils;
import pl.edu.agh.neuraleconomy.core.simulation.SimulationEngine;
import pl.edu.agh.neuraleconomy.core.simulation.Transaction;
import pl.edu.agh.neuraleconomy.core.ta.advice.Advice;

public class ChartStatistic implements IStatistic {
	private Logger logger = Logger.getLogger(getClass());
	
	private ArrayList<Double> serie = new ArrayList<Double>();
	private String chartName;
	private String serieName;
	private String yAxisName;
	private String fileName;
	private File dir;

	public ChartStatistic(String chartName, String serieName, String yAxisName, File dir, String fileName) {
		this.chartName = chartName;
		this.serieName = serieName;
		this.yAxisName = yAxisName;
		this.dir = dir;
		this.fileName = fileName;
	}

	public void iteration(Date date, SimulationEngine simulation, List<Advice> advices, List<Transaction> transactionsMade) {
		serie.add(Double.valueOf(simulation.getWealth().doubleValue()));
	}

	public void finalizeStatistic() {
		File f = null;
		try {
			JFreeChart chart = createChart();
			f = File.createTempFile(fileName, ".png", dir);
			ChartUtilities.saveChartAsPNG(f, chart, 600, 400);
		} catch (Exception e) {
			logger.error("", e);
			FileUtils.deleteQuietly(f);
		}
	}

	private JFreeChart createChart() {
		JFreeChart chart = ChartFactory.createXYLineChart(chartName, "Timeline", yAxisName, createDataSet(), PlotOrientation.VERTICAL, true,
				false, false);

		XYPlot xyPlot = (XYPlot) chart.getPlot();
		NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
		domain.setTickUnit(new NumberTickUnit(serie.size() < 75 ? 1 : 5));
		domain.setVerticalTickLabels(true);
		
		ValueAxis rangeAxis = xyPlot.getRangeAxis();
		rangeAxis.setRange(Collections.min(serie), Collections.max(serie));

		return chart;
	}

	private XYDataset createDataSet() {
		XYSeriesCollection data = new XYSeriesCollection();

		XYSeries s = new XYSeries(serieName);

		for (int i = 0; i < serie.size(); i++) {
			s.add(i, serie.get(i));
		}

		data.addSeries(s);

		return data;
	}

}
